﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using Meraz.Core.Config;

namespace Meraz.Core.Cache
{
    public class CacheManager<T>
    {
        private string m_cachekey = "";
        public string CacheKey
        {
            get { return m_cachekey; }
            set { m_cachekey = value; }
        }

        private int m_cacheduration;
        public int CacheDuration
        {
            get { return m_cacheduration; }
            set { m_cacheduration = value; }
        }

        public CacheManager(string Key, int duration)
        {
            this.CacheKey = Key;
            this.CacheDuration = duration;
        }

        public CacheManager(CacheKey key, int duration)
        {
            this.CacheKey = key.ToString();
            this.CacheDuration = duration;
        }

        public T Grab()
        {

            if (CheckCache())
                return (T)HttpContext.Current.Cache[this.CacheKey];
            else
                return default(T);
        }

        public void Insert(T obj, System.Web.Caching.CacheItemPriority priority)
        {

            if (CheckCache())
            {
                DateTime expiration = DateTime.Now.AddMinutes(this.CacheDuration);
                HttpContext.Current.Cache.Add(this.CacheKey, obj, null, expiration, TimeSpan.Zero, priority, null);
            }
        }

        public void Clear()
        {
            if (CheckCache())
                HttpContext.Current.Cache.Remove(this.CacheKey);
        }
        public bool CheckCache()
        {
            return ConfigHelper.CacheObjects == "true";
        }

    }
}
